package com.example.dicos.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import com.example.dicos.config.CommonResult;
import com.example.dicos.entity.WxPermission;
import com.example.dicos.entity.WxUser;
import com.example.dicos.mapper.WxUserMapper;
import com.example.dicos.service.WxUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author 开发者
 * @since 2022-07-11
 */
@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    private WxUserMapper wxUserMapper;

    /**
     * 用户登录
     *
     * @param userName
     * @return
     */
    @Override
    public WxUser queryName(String userName, String password) throws Exception {
        WxUser user = wxUserMapper.queryName(userName);
        if (ObjectUtils.isEmpty(user)) {
            throw new Exception("用户不存在");
        }
        String ps = user.getPassword();
        String salt = user.getSalt();//盐
        String md5 = SaSecureUtil.md5BySalt(password, salt);
        if (!ps.equals(md5)) {
            throw new Exception("账号或密码错误");
        }
        StpUtil.login(user.getId(), "user");
        StpUtil.getSession().set("user", user);

        //用户权限
//        List<WxPermission> userById = this.permissionUserById(user.getId());
        // 将权限list 转化为set形式
//        HashSet<WxPermission> wxPermissions = new HashSet<>(userById);
        // 将权限设置到用户实例中
//        user.setAuthorities(wxPermissions);
        //生成token
        String tokenValue = StpUtil.getTokenValue();
        user.setSatoken(tokenValue);

        return user;
    }

    @Override
    public WxUser queryById(Long userId) {
        return wxUserMapper.queryById(userId);
    }


    /**
     * 校验用户是否包含当前权限
     */
    @Autowired
    private StpInterfaceImpl stpInterface;

    /**
     * 注册
     *
     * @param wxUser
     * @return
     */
    @Override
    public Integer addUser(WxUser wxUser) throws Exception {
        WxUser userName = wxUserMapper.queryName(wxUser.getUserName());
        if (!ObjectUtils.isEmpty(userName)) {
            throw new Exception("该账号已经存在");
        }
        StpUtil.login(userName.getId());
        String salt = SaFoxUtil.getRandomString(10);//盐
        String md5 = SaSecureUtil.md5BySalt(wxUser.getPassword(), salt);
        wxUser.setPassword(md5);
        wxUser.setSalt(salt);
        wxUser.setCreateTime(new Date());
        wxUser.setLoginTime(new Date());
        wxUser.setStatus(1); //帐号启用状态：0->禁用；1->启用
        wxUser.setNote("备注信息");
        return wxUserMapper.addUser(wxUser);
    }


    /**
     * 获取当前登录用户的所有权限
     */
    @Override
    public List<WxPermission> permissionUserById(Object id) {

        return wxUserMapper.permissionUserById(id);
    }

    /**
     * 查询权限列表
     *
     * @return
     */
    @Override
    public List<WxPermission> permissionList() {
        return wxUserMapper.permissionList();
    }


    /**
     * 判断 该用户的权限
     */
    @Override
    public CommonResult list(String uri, String username) {

        List<WxPermission> permissionList = this.permissionList();
        boolean match = permissionList.stream().anyMatch(wxPermission -> StringUtils.equals(wxPermission.getUri(), uri));
        if (!match) {
            return CommonResult.success(true, "判断权限未通过！！~~~~");
        }
        WxUser wxUser = wxUserMapper.queryName(username);
        List<WxPermission> permissionsByUserId = this.permissionUserById(wxUser.getId());
        boolean b = permissionsByUserId.stream().anyMatch(wxPermission -> StringUtils.equals(wxPermission.getUri(), uri));
        return b ? CommonResult.success(true) : CommonResult.forbidden(null);
    }

    @Override
    public List<WxUser> selectListWxUser() {
        return wxUserMapper.selectListWxUser();
    }

}
